package config

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

// ConfigLoader 定义配置加载器接口
type ConfigLoader interface {
	Load(config interface{}) error
	LoadFromPath(path string, config interface{}) error
}

// YAMLConfigLoader 实现YAML配置加载
type YAMLConfigLoader struct{}

// NewYAMLConfigLoader 创建新的YAML配置加载器
func NewYAMLConfigLoader() *YAMLConfigLoader {
	return &YAMLConfigLoader{}
}

// Load 从默认路径加载配置
func (l *YAMLConfigLoader) Load(config interface{}) error {
	// 尝试从多个常见位置查找配置文件
	paths := []string{
		"config.yaml",
		"config.yml",
		"conf/config.yaml",
		"conf/config.yml",
		"/etc/cloud_android/config.yaml",
		"/etc/cloud_android/config.yml",
	}

	for _, path := range paths {
		if _, err := os.Stat(path); err == nil {
			return l.LoadFromPath(path, config)
		}
	}

	return errors.New("no configuration file found in default locations")
}

// LoadFromPath 从指定路径加载YAML配置
func (l *YAMLConfigLoader) LoadFromPath(path string, config interface{}) error {
	// 获取绝对路径
	absPath, err := filepath.Abs(path)
	if err != nil {
		return fmt.Errorf("failed to get absolute path: %v", err)
	}

	// 读取文件内容
	yamlFile, err := ioutil.ReadFile(absPath)
	if err != nil {
		return fmt.Errorf("failed to read config file: %v", err)
	}
	fmt.Printf("yaml file content:%s", string(yamlFile))
	// 解析YAML
	err = yaml.Unmarshal(yamlFile, config)
	if err != nil {
		return fmt.Errorf("failed to unmarshal YAML: %v", err)
	}

	return nil
}
